package com.jdk.demo.nio.bytebuffer;

import java.nio.ByteBuffer;

public class MarkDemo {

	public static void main(String[] args) {
		// 如果定义了mark，则在将position调整为不小于该mark的值时，该mark不丢弃
		m1();
		// 如果定义了mark，则在将position调整为小于该mark的值时，该mark被丢弃
		m2();
		// 如果定义了mark，则在将limit调整为不小于该mark的值时，该mark不丢弃
		m3();
		// 如果定义了mark，则在将limit调整为小于该mark的值时，该mark被丢弃
		m4();
	}

	public static void m1() {
		byte[] byteArray = new byte[] {1, 2, 3};
		ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);

		byteBuffer.position(1);
		byteBuffer.mark();
		System.out.println("bytebuffer在" + byteBuffer.position() + "位置设置mark标记");

		byteBuffer.position(2);
		byteBuffer.reset();
		System.out.println("bytebuffer回到" + byteBuffer.position() + "位置");
	}

	public static void m2() {
		byte[] byteArray = new byte[] {1, 2, 3};
		ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);

		byteBuffer.position(2);
		byteBuffer.mark();
		System.out.println("bytebuffer在" + byteBuffer.position() + "位置设置mark标记");

		byteBuffer.position(1);
		try {
			byteBuffer.reset();
		}catch (Exception e) {
			System.out.println("bytebuffer的mark标记无效");
		}
	}

	public static void m3() {
		byte[] byteArray = new byte[] {1, 2, 3};
		ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);

		System.out.println("A bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		byteBuffer.position(2);
		byteBuffer.mark();
		System.out.println("B bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		byteBuffer.position(3);
		byteBuffer.limit(3);
		System.out.println("C bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		byteBuffer.reset();
		System.out.println("D bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());
	}

	public static void m4() {
		byte[] byteArray = new byte[] {1, 2, 3};
		ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);

		System.out.println("A bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		byteBuffer.position(2);
		byteBuffer.mark();
		System.out.println("B bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		byteBuffer.limit(1);
		System.out.println("C bytebuffer position=" + byteBuffer.position() + " limit=" + byteBuffer.limit());

		try {
			byteBuffer.reset();
		}catch (Exception e) {
			System.out.println("bytebuffer的mark标记无效");
		}
	}

}
